<?php
require_once __DIR__ . '/../functions.php';

// 检查管理员权限
if (!isAdmin()) {
    redirect('../index.php', '您没有权限访问管理后台', 'danger');
}

// 获取统计数据
$db = getDB();


// 新增：获取系统设置
$settings = [];
$stmt = $db->query("SELECT * FROM settings");
foreach ($stmt->fetchAll() as $setting) {
    $settings[$setting['key_name']] = $setting['key_value'];
}
// 用户统计
$stmt = $db->query("SELECT COUNT(*) as total, COUNT(CASE WHEN is_admin = 1 THEN 1 END) as admins FROM users WHERE status = 1");
$userStats = $stmt->fetch();

// 订单统计
$stmt = $db->query("SELECT 
    COUNT(*) as total,
    COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending,
    COUNT(CASE WHEN status = 'settled' THEN 1 END) as settled,
    COUNT(CASE WHEN status = 'refunded' THEN 1 END) as refunded,
    SUM(CASE WHEN status = 'settled' AND settlement_amount > 0 THEN settlement_amount ELSE 0 END) as total_settlement,
    SUM(order_amount) as total_order_amount
FROM orders");
$orderStats = $stmt->fetch();

// 今日统计
$today = date('Y-m-d');
$stmt = $db->prepare("SELECT 
    COUNT(*) as total_orders,
    SUM(order_amount) as total_amount,
    COUNT(CASE WHEN status = 'settled' THEN 1 END) as settled_orders,
    SUM(CASE WHEN status = 'settled' AND settlement_amount > 0 THEN settlement_amount ELSE 0 END) as settled_amount
FROM orders 
WHERE DATE(created_at) = ?");
$stmt->execute([$today]);
$todayStats = $stmt->fetch();

// 本周统计
$weekStart = date('Y-m-d', strtotime('monday this week'));
$weekEnd = date('Y-m-d', strtotime('sunday this week'));
$stmt = $db->prepare("SELECT 
    COUNT(*) as total_orders,
    SUM(order_amount) as total_amount,
    COUNT(CASE WHEN status = 'settled' THEN 1 END) as settled_orders
FROM orders 
WHERE DATE(created_at) BETWEEN ? AND ?");
$stmt->execute([$weekStart, $weekEnd]);
$weekStats = $stmt->fetch();

// 待结算统计
$stmt = $db->query("SELECT 
    COUNT(*) as pending_settlements,
    SUM(total_amount) as pending_amount,
    COUNT(DISTINCT user_id) as pending_users
FROM settlements 
WHERE status = 'pending'");
$settlementStats = $stmt->fetch();

// 最近7天订单趋势
$dates = [];
$orderCounts = [];
$settledCounts = [];
for ($i = 6; $i >= 0; $i--) {
    $date = date('Y-m-d', strtotime("-$i days"));
    $dates[] = $date;
    
    $stmt = $db->prepare("SELECT COUNT(*) as total, COUNT(CASE WHEN status = 'settled' THEN 1 END) as settled FROM orders WHERE DATE(created_at) = ?");
    $stmt->execute([$date]);
    $dayStats = $stmt->fetch();
    $orderCounts[] = $dayStats['total'];
    $settledCounts[] = $dayStats['settled'];
}

// 获取活跃用户（最近30天有订单的用户）
$stmt = $db->prepare("SELECT COUNT(DISTINCT user_id) as active_users FROM orders WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)");
$stmt->execute();
$activeUsers = $stmt->fetchColumn();

include __DIR__ . '/header.php';
?>

<div class="container-fluid">
    <!-- ... 原有代码 ... -->

            <!-- 统计卡片 -->
            
            <div class="row mb-4">
                <!-- 快递查询余额 -->
<div class="col-xl-3 col-md-6 mb-4">
    <div class="card border-left-info shadow h-100 py-2">
        <div class="card-body">
            <div class="row no-gutters align-items-center">
                <div class="col mr-2">
                    <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                        快递查询余额
                    </div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800">
                        <?php
                        // 确保余额是数字类型
                        $expressBalance = isset($settings['express_balance']) && $settings['express_balance'] !== '' 
                            ? floatval($settings['express_balance']) 
                            : 0.00;
                        echo '¥' . number_format($expressBalance, 2);
                        ?>
                    </div>
                    <div class="text-xs text-muted mt-1">
                        <?php 
                        $lastCheck = $settings['express_balance_updated'] ?? '';
                        echo $lastCheck ? '更新: ' . formatTime($lastCheck) : '从未检查';
                        ?>
                    </div>
                </div>
                <div class="col-auto">
                    <i class="bi bi-wallet2 fa-2x text-gray-300"></i>
                </div>
            </div>
            <?php if (!empty($settings['express_token'])): ?>
            <div class="mt-3 text-center">
                <button type="button" class="btn btn-sm btn-outline-info" onclick="updateExpressBalance()">
                    <i class="bi bi-arrow-repeat"></i> 更新余额
                </button>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>
                
                <div class="col-xl-3 col-md-6 mb-4">
                    <div class="card border-left-primary shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                        总用户数
                                    </div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800">
                                        <?php echo $userStats['total']; ?>
                                        <small class="text-sm text-muted">(管理员: <?php echo $userStats['admins']; ?>)</small>
                                    </div>
                                    <div class="text-xs text-muted mt-1">活跃用户: <?php echo $activeUsers; ?></div>
                                </div>
                                <div class="col-auto">
                                    <i class="bi bi-people fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-xl-3 col-md-6 mb-4">
                    <div class="card border-left-warning shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                        待处理订单
                                    </div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $orderStats['pending']; ?></div>
                                    <div class="text-xs text-muted mt-1">总订单: <?php echo $orderStats['total']; ?></div>
                                </div>
                                <div class="col-auto">
                                    <i class="bi bi-hourglass-split fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-xl-3 col-md-6 mb-4">
                    <div class="card border-left-success shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                        已结算订单
                                    </div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $orderStats['settled']; ?></div>
                                    <div class="text-xs text-muted mt-1">总结算: ¥<?php echo number_format($orderStats['total_settlement'], 2); ?></div>
                                </div>
                                <div class="col-auto">
                                    <i class="bi bi-check-circle-fill fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-xl-3 col-md-6 mb-4">
                    <div class="card border-left-info shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                        总订单金额
                                    </div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800">¥<?php echo number_format($orderStats['total_order_amount'], 2); ?></div>
                                    <div class="text-xs text-muted mt-1">已退还: <?php echo $orderStats['refunded']; ?> 单</div>
                                </div>
                                <div class="col-auto">
                                    <i class="bi bi-currency-yen fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 今日和本周统计 -->
            <div class="row mb-4">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h6 class="m-0 font-weight-bold text-primary">
                                <i class="bi bi-calendar-day"></i> 今日统计
                            </h6>
                        </div>
                        <div class="card-body">
                            <div class="row text-center">
                                <div class="col-6">
                                    <h4 class="text-primary"><?php echo $todayStats['total_orders'] ?? 0; ?></h4>
                                    <p class="text-muted">今日订单数</p>
                                </div>
                                <div class="col-6">
                                    <h4 class="text-success">¥<?php echo number_format($todayStats['total_amount'] ?? 0, 2); ?></h4>
                                    <p class="text-muted">今日订单金额</p>
                                </div>
                                <div class="col-6">
                                    <h4 class="text-info"><?php echo $todayStats['settled_orders'] ?? 0; ?></h4>
                                    <p class="text-muted">今日结算订单</p>
                                </div>
                                <div class="col-6">
                                    <h4 class="text-warning">¥<?php echo number_format($todayStats['settled_amount'] ?? 0, 2); ?></h4>
                                    <p class="text-muted">今日结算金额</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h6 class="m-0 font-weight-bold text-primary">
                                <i class="bi bi-calendar-week"></i> 本周统计
                            </h6>
                        </div>
                        <div class="card-body">
                            <div class="row text-center">
                                <div class="col-6">
                                    <h4 class="text-primary"><?php echo $weekStats['total_orders'] ?? 0; ?></h4>
                                    <p class="text-muted">本周订单数</p>
                                </div>
                                <div class="col-6">
                                    <h4 class="text-success">¥<?php echo number_format($weekStats['total_amount'] ?? 0, 2); ?></h4>
                                    <p class="text-muted">本周订单金额</p>
                                </div>
                                <div class="col-6">
                                    <h4 class="text-info"><?php echo $weekStats['settled_orders'] ?? 0; ?></h4>
                                    <p class="text-muted">本周结算订单</p>
                                </div>
                                <div class="col-6">
                                    <h4 class="text-warning"><?php echo $settlementStats['pending_settlements'] ?? 0; ?></h4>
                                    <p class="text-muted">待结算账单</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 待结算统计 -->
            <div class="card mb-4">
                <div class="card-header">
                    <h6 class="m-0 font-weight-bold text-warning">
                        <i class="bi bi-clock-history"></i> 待结算统计
                    </h6>
                </div>
                <div class="card-body">
                    <div class="row text-center">
                        <div class="col-md-4">
                            <h3 class="text-warning"><?php echo $settlementStats['pending_settlements'] ?? 0; ?></h3>
                            <p class="text-muted">待结算账单数</p>
                        </div>
                        <div class="col-md-4">
                            <h3 class="text-danger">¥<?php echo number_format($settlementStats['pending_amount'] ?? 0, 2); ?></h3>
                            <p class="text-muted">待结算总金额</p>
                        </div>
                        <div class="col-md-4">
                            <h3 class="text-info"><?php echo $settlementStats['pending_users'] ?? 0; ?></h3>
                            <p class="text-muted">待结算用户数</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 订单趋势图 -->
            <div class="card mb-4">
                <div class="card-header">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="bi bi-graph-up"></i> 最近7天订单趋势
                    </h6>
                </div>
                <div class="card-body">
                    <canvas id="orderChart" width="400" height="100"></canvas>
                </div>
            </div>

            <!-- 最新订单 -->
            <div class="card mb-4">
                <div class="card-header">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="bi bi-clock"></i> 最新订单
                    </h6>
                </div>
                <div class="card-body">
                    <?php
                    $stmt = $db->query("SELECT o.*, u.username, u.phone FROM orders o 
                                       LEFT JOIN users u ON o.user_id = u.id 
                                       ORDER BY o.created_at DESC LIMIT 5");
                    $recentOrders = $stmt->fetchAll();
                    ?>
                    
                    <?php if (empty($recentOrders)): ?>
                        <div class="text-center py-4">
                            <i class="bi bi-inbox display-4 text-muted"></i>
                            <p class="text-muted mt-2">暂无订单</p>
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>商品名称</th>
                                        <th>用户</th>
                                        <th>金额</th>
                                        <th>状态</th>
                                        <th>时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($recentOrders as $order): ?>
                                        <tr>
                                            <td><?php echo $order['id']; ?></td>
                                            <td><?php echo htmlspecialchars($order['product_name']); ?></td>
                                            <td><?php echo htmlspecialchars($order['username']); ?></td>
                                            <td><?php echo formatAmount($order['order_amount']); ?></td>
                                            <td>
                                                <span class="badge bg-<?php echo getOrderStatusClass($order['status']); ?>">
                                                    <?php echo getOrderStatusText($order['status']); ?>
                                                </span>
                                            </td>
                                            <td><?php echo formatTime($order['created_at']); ?></td>
                                            <td>
                                                <a href="orders.php?action=edit&id=<?php echo $order['id']; ?>" 
                                                   class="btn btn-sm btn-outline-primary">
                                                    <i class="bi bi-pencil"></i> 处理
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        
                        <div class="text-center mt-3">
                            <a href="orders.php" class="btn btn-primary">
                                <i class="bi bi-list-check"></i> 查看所有订单
                            </a>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
</div>
<?php include __DIR__ . '/footer.php'; ?>
<script src="../js/chart.min.js"></script>

<script>
// 确保在 DOM 加载完成后初始化图表
document.addEventListener('DOMContentLoaded', function() {
    const ctx = document.getElementById('orderChart');
    if (ctx) {
        const orderChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: <?php echo json_encode(array_map(function($date) {
                    return date('m/d', strtotime($date));
                }, $dates)); ?>,
                datasets: [{
                    label: '总订单',
                    data: <?php echo json_encode($orderCounts); ?>,
                    borderColor: 'rgb(75, 192, 192)',
                    backgroundColor: 'rgba(75, 192, 192, 0.2)',
                    tension: 0.1,
                    fill: true
                }, {
                    label: '已结算',
                    data: <?php echo json_encode($settledCounts); ?>,
                    borderColor: 'rgb(54, 162, 235)',
                    backgroundColor: 'rgba(54, 162, 235, 0.2)',
                    tension: 0.1,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1
                        }
                    }
                }
            }
        });
    }
});

// 更新快递查询余额
function updateExpressBalance() {
    const button = event.target;
    const originalText = button.innerHTML;
    button.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> 更新中...';
    button.disabled = true;

    fetch('api/express_query.php?action=check_balance')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast(`余额更新成功: ¥${data.balance}`, 'success');
                setTimeout(() => {
                    location.reload();
                }, 1500);
            } else {
                showToast('余额更新失败: ' + data.message, 'danger');
                button.innerHTML = originalText;
                button.disabled = false;
            }
        })
        .catch(error => {
            showToast('请求失败: ' + error.message, 'danger');
            button.innerHTML = originalText;
            button.disabled = false;
        });
}

// 简单的提示函数
function showToast(message, type = 'info') {
    // 创建临时提示
    const toast = document.createElement('div');
    toast.className = `alert alert-${type} alert-dismissible fade show`;
    toast.style.position = 'fixed';
    toast.style.top = '20px';
    toast.style.right = '20px';
    toast.style.zIndex = '9999';
    toast.style.minWidth = '300px';
    toast.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(toast);
    
    // 自动移除
    setTimeout(() => {
        if (toast.parentNode) {
            toast.parentNode.removeChild(toast);
        }
    }, 3000);
}
</script>

